package com.syuson.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 通过过滤器基于request对象初始化并缓存记录当前应用上下文路径
 * 
 * @author syuson
 *
 */
public class WebAppContextInitFilter implements Filter {

	private static String WEB_CONTEXT_FULL_URL = null;
	private static String WEB_CONTEXT_REAL_PATH = null;

	public void destroy() {
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

	public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		//设置当前WEB_ROOT根目录到配置属性以便在单纯的Service运行环境取到应用根目录获取WEB-INF下相关资源
		if (WEB_CONTEXT_FULL_URL == null) {
			WEB_CONTEXT_REAL_PATH = request.getServletContext().getRealPath("/");
		}
		chain.doFilter(req, rep);
	}

	public static String getInitedWebContextRealPath() {
		return WEB_CONTEXT_REAL_PATH;
	}

	public static void reset() {
		WEB_CONTEXT_FULL_URL = null;
		WEB_CONTEXT_REAL_PATH = null;
	}

}
